package com.wyd.proxy;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.util.EntityUtils;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.Properties;

// 根据请求参数转发到不同系统
public class MyProxyServlet2 extends ProxyServlet {
    private static final Properties proxyProperties = new Properties();

    // 构造代码块
    {
        try {
            // 初始化接口映射文件，在此创建公共缓存，消除重复解析文件过程
            proxyProperties.load(new InputStreamReader(Objects.requireNonNull(MyProxyServlet2.class.getClassLoader().getResourceAsStream("proxy.properties"))));
        } catch (IOException e) {
            super.log("初始化接口映射文件加载失败");
        }
    }

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
        final String[] addrs = servletRequest.getParameterValues("addr");
        if (addrs == null || addrs.length == 0) {
            servletResponse.sendError(400, "缺少必要参数");
            return;
        }

        // 代理地址
        String targetUri = proxyProperties.getProperty(addrs[0]);
        if (ObjectUtils.isEmpty(targetUri)) {
            servletResponse.sendError(404, "未知链接");
            return;
        }

        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);

        try {
            servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(new URI(targetUri)));
        } catch (URISyntaxException e) {
            servletResponse.sendError(404, "链接无效");
            return;
        }

        super.service(servletRequest, servletResponse);
    }

    @Override
    protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse, HttpRequest proxyRequest, HttpServletRequest servletRequest) throws IOException {
//        super.copyResponseEntity(proxyResponse, servletResponse, proxyRequest, servletRequest);
        HttpEntity entity = proxyResponse.getEntity();
        if (entity != null) {
            OutputStream servletOutputStream = servletResponse.getOutputStream();

            if (entity.getContentType().getValue().equalsIgnoreCase("application/json")) {
                final String data = EntityUtils.toString(entity);
                System.out.printf("返回数据%s\n", data);

                servletOutputStream.write(data.getBytes());
            } else {

                entity.writeTo(servletOutputStream);
            }
        }
    }
}
